<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>角色管理</title>
    <link rel="stylesheet" href="/static/css/admin.css">
</head>
<body>
    <div th:fragment="content">
        <div class="d-flex justify-content-between mb-3">
            <h2>角色管理</h2>
            <button class="btn btn-purple" onclick="showRoleModal()">
                <i class="bi bi-plus-lg"></i> 新增角色
            </button>
        </div>

        <div class="card shadow-sm">
            <div class="card-header" style="background: linear-gradient(45deg, var(--primary-dark), var(--primary-color));">
                <h5 class="card-title mb-0 text-white">角色列表</h5>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-4">
                        <input type="text" class="form-control" id="searchRoleName" placeholder="搜索角色名称">
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-purple" onclick="searchRoles()">
                            <i class="bi bi-search"></i> 搜索
                        </button>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr style="background: linear-gradient(45deg, var(--primary-dark), var(--primary-color)); color: white;">
                                <th>角色名称</th>
                                <th>角色标识</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="roleTableBody">
                            <tr th:each="role : ${roles}">
                                <td th:text="${role.name}"></td>
                                <td th:text="${role.code}"></td>
                                <td>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" 
                                            type="checkbox" 
                                            th:checked="${role.status == 1}"
                                            th:onchange="'toggleRoleStatus(' + ${role.id} + ', this)'">
                                    </div>
                                </td>
                                <td th:text="${#dates.format(role.createDate, 'yyyy-MM-dd HH:mm')}"></td>
                                <td>
                                    <button class="btn btn-sm btn-purple" 
                                        th:onclick="'editRole(' + ${role.id} + ')'">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button class="btn btn-sm btn-purple"
                                        th:onclick="'assignMenus(' + ${role.id} + ')'">
                                        <i class="bi bi-list-task"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger" 
                                        th:onclick="'deleteRole(' + ${role.id} + ')'">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <nav>
                    <ul class="pagination justify-content-center">
                        <li class="page-item" th:classappend="${page.current == 1} ? 'disabled'">
                            <a class="page-link" href="#" th:onclick="'changePage(' + ${page.current - 1} + ')'">上一页</a>
                        </li>
                        <li class="page-item" th:each="i : ${#numbers.sequence(1, page.pages)}"
                            th:classappend="${i == page.current} ? 'active'">
                            <a class="page-link" href="#" th:onclick="'changePage(' + ${i} + ')'" th:text="${i}"></a>
                        </li>
                        <li class="page-item" th:classappend="${page.current == page.pages} ? 'disabled'">
                            <a class="page-link" href="#" th:onclick="'changePage(' + ${page.current + 1} + ')'">下一页</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>

        <!-- Role Modal -->
        <div class="modal fade" id="roleModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header" style="background: linear-gradient(45deg, var(--primary-dark), var(--primary-color));">
                        <h5 class="modal-title text-white" id="roleModalTitle">新增角色</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="roleForm">
                            <div class="mb-3">
                                <label for="roleName" class="form-label">角色名称</label>
                                <input type="text" class="form-control" id="roleName" required>
                            </div>
                            <div class="mb-3">
                                <label for="roleCode" class="form-label">角色标识</label>
                                <input type="text" class="form-control" id="roleCode" required>
                            </div>
                            <div class="mb-3">
                                <label for="roleStatus" class="form-label">状态</label>
                                <select class="form-select" id="roleStatus">
                                    <option value="1">启用</option>
                                    <option value="0">禁用</option>
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-purple" onclick="saveRole()">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <script>
            let currentRoleId = null;

            function showRoleModal(role) {
                const modal = new bootstrap.Modal('#roleModal');
                if (role) {
                    currentRoleId = role.id;
                    document.getElementById('roleModalTitle').textContent = '编辑角色';
                    document.getElementById('roleName').value = role.name;
                    document.getElementById('roleCode').value = role.code;
                    document.getElementById('roleStatus').value = role.status;
                } else {
                    currentRoleId = null;
                    document.getElementById('roleModalTitle').textContent = '新增角色';
                    document.getElementById('roleForm').reset();
                }
                modal.show();
            }

            function saveRole() {
                const roleData = {
                    name: document.getElementById('roleName').value,
                    code: document.getElementById('roleCode').value,
                    status: document.getElementById('roleStatus').value
                };

                const url = currentRoleId 
                    ? `/api/admin/roles/${currentRoleId}`
                    : '/api/admin/roles';

                const method = currentRoleId ? 'PUT' : 'POST';

                axios({
                    method: method,
                    url: url,
                    data: roleData
                }).then(response => {
                    location.reload();
                }).catch(error => {
                    alert('保存失败：' + error.response.data.message);
                });
            }

            function deleteRole(roleId) {
                if (confirm('确定要删除该角色吗？')) {
                    axios.delete(`/api/admin/roles/${roleId}`)
                        .then(response => {
                            location.reload();
                        })
                        .catch(error => {
                            alert('删除失败：' + error.response.data.message);
                        });
                }
            }

            function toggleRoleStatus(roleId, checkbox) {
                const status = checkbox.checked ? 1 : 0;
                axios.patch(`/api/admin/roles/${roleId}/status`, { status })
                    .catch(error => {
                        alert('状态更新失败：' + error.response.data.message);
                        checkbox.checked = !checkbox.checked;
                    });
            }

            function assignMenus(roleId) {
                axios.get(`/api/admin/roles/${roleId}/menus`)
                    .then(response => {
                        const menus = response.data;

                        const modalContent = `
                            <div class="modal-dialog modal-lg">
                                <div class="modal-content">
                                    <div class="modal-header" style="background: linear-gradient(45deg, var(--primary-dark), var(--primary-color));">
                                        <h5 class="modal-title text-white">分配菜单</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="row">
                                            ${menus.map(menu => `
                                                <div class="col-md-4">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" 
                                                            id="menu-${menu.id}" value="${menu.id}"
                                                            ${menu.assigned ? 'checked' : ''}>
                                                        <label class="form-check-label" for="menu-${menu.id}">
                                                            ${menu.name}
                                                        </label>
                                                    </div>
                                                </div>
                                            `).join('')}
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                        <button type="button" class="btn btn-purple" onclick="saveRoleMenus(${roleId})">保存</button>
                                    </div>
                                </div>
                            </div>
                        `;

                        const modal = new bootstrap.Modal(document.createElement('div'));
                        modal._element.innerHTML = modalContent;
                        modal.show();
                    })
                    .catch(error => {
                        alert('获取菜单信息失败：' + error.response.data.message);
                    });
            }

            function saveRoleMenus(roleId) {
                const selectedMenus = Array.from(document.querySelectorAll('input[type="checkbox"]:checked'))
                    .map(checkbox => checkbox.value);

                axios.put(`/api/admin/roles/${roleId}/menus`, { menus: selectedMenus })
                    .then(response => {
                        location.reload();
                    })
                    .catch(error => {
                        alert('保存菜单分配失败：' + error.response.data.message);
                    });
            }

            function searchRoles() {
                const roleName = document.getElementById('searchRoleName').value;
                window.location.href = `/admin/roles?name=${roleName}`;
            }

            function changePage(page) {
                window.location.href = `/admin/roles?page=${page}`;
            }
        </script>
    </div>
</body>
</html>
